package bard.partnermatchingsystem.job;

import bard.partnermatchingsystem.domain.po.User;
import bard.partnermatchingsystem.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PreCacheJob {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private UserService userService;
    @Autowired
    private RedissonClient redissonClient;

    private List<Long> mainUserIdList= Arrays.asList(1L);
    @Scheduled(cron = "0 13 21 * * ? ")
    public void doRecommendCache() {
        RLock lock = redissonClient.getLock("bard:user:recommend:lock");
        try {
            if (lock.tryLock(0,-1, TimeUnit.MILLISECONDS)){
                ValueOperations<String, Object> Operations = redisTemplate.opsForValue();
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                for (Long userId : mainUserIdList) {
                    log.info("doRecommendCache start");
                    String redisKey = String.format("bard:user:recommend:%s", userId);
                    try {
                        Operations.set(redisKey, userPage,23,TimeUnit.HOURS );
                    } catch (Exception e) {
                        log.error("redis set key error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("doRecommendCache error", e);
        }
        finally {
            // 只能释放自己的锁
            if(lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
